from flask import url_for
from flask_restful import Resource

from model.crud import QueryOneInstance
from model.tables import Blog
from restful.data import DataPid
from restful.error import RenderPostNotExist, RenderPostNotPublic
from restful.request import Get
from restful.response import ResponseSuccess
from restful.session import login_required, data, current_user_required


class PostDetail(Resource):
    @current_user_required
    @data(DataPid())
    def get(self, data,current_user):
        post=QueryOneInstance(Blog,{'id':data['pid']})
        if not post:
            return RenderPostNotExist(data['pid'])

        if post.uid != current_user.id:
            if not post.checked or not post.passed:
                return RenderPostNotPublic(data['pid'])

        postcomment_data=Get(url_for('postcomment',pid=post.id,_external=True))
        postlike_data=Get(url_for('postlike',pid=post.id,_external=True))

        return ResponseSuccess(data={
            'comments':postcomment_data,
            **postlike_data,
            'uid':post.uid,
            'time':post.time,
            'content':post.content,
            'sort':post.sort,
            'title':post.title,
            'checked':post.checked,
            'passed':post.passed,
            'reason':post.reason,
        })

